from .base_handler import BaseRequestHandler
import time
from .tdp_slave_handler import TdpSlaveWebsocketHandler


class TdpSlaveGroupManageHandler(BaseRequestHandler):
    """执行机组 管理"""
    did_not_group_id = 1
    async def get_default(self):
        """查询所有执行机组信息，包含它所拥有的执行机数量"""
        data = await self.mdb.query(
            '''
            select sg.*, creator.real_name as creator_name
            , ifnull(msg.slave_count, 0) as slave_count
            from tdp_slave_group sg
              left join tdp_user creator on sg.creator_id=creator.id
              left join (select slave_group_id, count(1) as slave_count from map_tdp_slave2group group by slave_group_id) msg
                on msg.slave_group_id = sg.id
            where sg.id != %s
            ''', self.did_not_group_id  # 排除掉未分组（后面单独查）
        )
        data_not_group_slave_count = (await self.mdb.query_one(
            '''
              SELECT COUNT(id) FROM tdp_slave t
              LEFT JOIN (SELECT COUNT(1) AS c, slave_id FROM map_tdp_slave2group GROUP BY slave_id) m ON m.slave_id=t.id
              WHERE m.c IS NULL
              '''
        ))['COUNT(id)']  # 未分组的执行机数量
        data_not_group = await self.mdb.query_one_by_dict(table='tdp_slave_group', col=('*', "'' as create_time"), where={'id': self.did_not_group_id})  # 未分组的分组信息
        data_not_group['slave_count'] = data_not_group_slave_count
        data.insert(0, data_not_group)
        self.success_data = data

    async def get_slaveInfo(self):
        """查询 单个执行机组中的 所有执行机信息"""
        slave_group_id = self.get_argument('group_id')
        if int(slave_group_id) == self.did_not_group_id:  # 如果为未分组的ID
            data = await self.mdb.query(
                '''
                SELECT t.*, creator.real_name as creator_name FROM tdp_slave t
                  left join tdp_user creator on t.creator_id=creator.id
                  LEFT JOIN (SELECT COUNT(1) AS c, slave_id FROM map_tdp_slave2group GROUP BY slave_id) m 
                    ON m.slave_id=t.id
                WHERE m.c IS NULL
                '''
            )
        else:
            data = await self.mdb.query(
                '''
                  select s.*, creator.real_name as creator_name
                  from tdp_slave_group sg, tdp_slave s
                    left join tdp_user creator on s.creator_id=creator.id
                  , map_tdp_slave2group msg
                  where sg.id=%s and sg.id=msg.slave_group_id and s.id=msg.slave_id
                  ''', slave_group_id
            )
        self.success_data = data

    async def get_notInGroupSlaveInfo(self):
        """查询 不在当前执行机组的 所有执行机信息 （添加执行机时需要排除已经添加过的）"""
        slave_group_id = self.get_argument('group_id')
        data = await self.mdb.query(
            '''
              select s.*
              from tdp_slave s 
              where s.id not in (select slave_id from map_tdp_slave2group where slave_group_id=%s) and s.if_accept=1
              ''', slave_group_id
        )
        self.success_data = data

    async def post_addSlave(self):
        """添加执行机 到执行机组"""
        slave_id_list = self.request_json
        slave_group_id = self.get_argument('group_id')
        for slave_id in slave_id_list:
            await self.mdb.insert_by_dict(
                table='map_tdp_slave2group',
                data={'slave_id': slave_id, 'slave_group_id': slave_group_id}
            )

    async def post_groupInfo(self):
        group_id = self.get_argument('id')
        data = await self.mdb.query_by_dict(
            table='tdp_slave_group',
            col=('*', "date_format(create_time,'%%Y-%%m-%%d %%H:%%i:%%s') AS create_time"),
            where={'id': group_id}
        )
        self.success_data = data

    async def post_edit(self):
        """新增、编辑执行机组信息"""
        group_id = self.get_argument('id', None)
        data = {
            'group_name': self.get_escaped_argument('group_name'),
            'mark': self.get_argument('mark'),
        }
        if group_id:  # 更新
            data['last_mender_id'] = self.current_user_id
            if int(group_id) == self.did_not_group_id:
                raise Exception('该分组不能编辑！')
            else:
                await self.mdb.update_by_dict(table='tdp_slave_group', colv=data, where={'id': group_id})
        else:  # 新增
            data['creator_id'] = self.current_user_id
            data['create_time'] = self.now_strftime()
            await self.mdb.insert_by_dict(table='tdp_slave_group', data=data)

    async def post_del(self):
        """删除 单个 执行机组"""
        group_id = self.get_argument('id')
        if int(group_id) != self.did_not_group_id:
            await self.mdb.delete_by_dict(table='tdp_slave_group', where={'id': group_id})
            self.success_data = '删除成功！'
        else:
            self.success_data = '不能删除此分组！'

    async def post_delSlave(self):
        """从指定执行机组 删除 指定执行机"""
        slave_id_list = self.request_json
        slave_group_id = self.get_argument('group_id')
        if int(slave_group_id) != self.did_not_group_id:
            for slave_id in slave_id_list:
                await self.mdb.delete_by_dict(
                    table='map_tdp_slave2group',
                    where={'slave_id': slave_id, 'slave_group_id': slave_group_id}
                )
        else:
            for sid in slave_id_list:
                await TdpSlaveWebsocketHandler.delete_slave(sid)


class TdpSlaveManageHandler(BaseRequestHandler):
    """执行机 管理"""
    async def get_acceptedSlaves(self):
        """查询所有 已被管理的执行机"""
        self.success_data = await self.mdb.query_by_dict(table='tdp_slave', where={'if_accept': 1})
        self.success_data = await self.mdb.query(
            '''
            select s.*, creator.real_name as creator_name from tdp_slave s 
              left join tdp_user creator on s.creator_id=creator.id
            where s.if_accept=1
            '''
        )

    async def get_breakSlave(self):
        """断开执行机的连接"""
        sid = self.get_argument('slaveId')
        if sid in TdpSlaveWebsocketHandler.slave:
            if 'Sid' in self.request.headers:
                del (self.request.headers['Sid'])
                self.request.headers.add('Sid', sid)  # websocket断开时需要使用请求头中的sid参数
            TdpSlaveWebsocketHandler.slave[sid]['handler'].write_message({'msg': '该执行机已被服务器断开连接!'})
            TdpSlaveWebsocketHandler.slave[sid]['handler'].close()
            TdpSlaveWebsocketHandler.slave.pop(sid)
        else:
            await self.mdb.execute("update tdp_slave set status='off-line', parallel_now=0 where id=%s", sid)

    async def post_default(self):
        """获取指定执行机信息"""
        slave_id = self.get_argument('id')
        data = await self.mdb.query('select * from tdp_slave where id=%s', slave_id)
        self.success_data = data

    async def post_edit(self):
        """修改 执行机信息"""
        slave_id = self.get_argument('id')
        parallel_max = self.get_escaped_argument('parallel_max', '1')
        data = {
            'slave_name': self.get_escaped_argument('slave_name'),
            'parallel_max': parallel_max,
            'work_path': self.get_escaped_argument('work_path', './'),
            'mark': self.get_argument('mark'),
        }
        await self.mdb.update_by_dict(table='tdp_slave', colv=data, where={'id': slave_id})

    async def post_add(self):
        """添加 执行机"""
        slave_id = self.get_argument('id')
        d = {
            'if_accept': 1,
            'creator_id': self.current_user_id,
            'create_time': time.strftime("%Y-%m-%d %H:%M:%S")
        }
        await self.mdb.update_by_dict(table='tdp_slave', colv=d, where={'id': slave_id})

    async def post_del(self):
        """删除 执行机"""
        slave_id = self.get_argument('id')
        await TdpSlaveWebsocketHandler.delete_slave(slave_id)


